/**
 * 微信视频号直播数据弹窗模组
 * 处理直播数据记录和显示
 */
import cssText from "data-text:~/assets/css/data_screen.css"
import antdResetCssText from "data-text:antd/dist/reset.css"
import moment from "moment"
import type {
  PlasmoCSConfig,
  PlasmoGetRootContainer,
  PlasmoGetShadowHostId
} from "plasmo"
import React, { useEffect, useState } from "react"
import { usePort } from "@plasmohq/messaging/hook"
import DataRecordModalIndex from "~ui_components/DataRecordModalIndex"

// 注入配置
export const config: PlasmoCSConfig = {
  matches: [
    // 微信视频号直播数据大屏(专业版)
    "https://channels.weixin.qq.com/platform/statistic/dashboardV4*",
  ],
  run_at: "document_end",
  all_frames: true
}

// 注入的shadow dom的id
export const HOST_ID = "data-record-modal"
export const getShadowHostId: PlasmoGetShadowHostId = () => HOST_ID

// 注入样式
export const getStyle = () => {
  const style = document.createElement("style")
  style.textContent = cssText + antdResetCssText
  return style
}

const WxDataRecordModal: React.FC = () => {
  // const [hijackData, setHijackData] = useState({})
  // 大屏数据处理port
  const wxLiveScreenData = usePort("wxLiveScreenData")

  // hijack事件响应方法
  const eventHandler = (event: CustomEvent<{
    type: string;
    url: string;
    method: string;
    response: any;
  }>) => {
    wxLiveScreenData.send(event.detail)
  }

  // 启动事件监听
  useEffect(() => {
    // 发送初始化消息
    wxLiveScreenData.send({ action: "init" })
    // 启动事件监听
    window.addEventListener("wxLiveHijackData", eventHandler)
    // 清理事件监听
    return () => {
      window.removeEventListener("wxLiveHijackData", eventHandler)
    }
  }, [])

  return <DataRecordModalIndex HostId={HOST_ID} hijackData={wxLiveScreenData.data} />
}

export default WxDataRecordModal
